<template>
  <view class="message-page">
    <view class="message-header">
      <view class="notification-prompt" >
        <text>点击管理通知，不错过消息提醒</text>
        <button class="manage-button" type="primary" size="mini" >去管理</button>
      </view>
      <view class="message-action">
        <view class="action-item">
          <image class="action-icon" src="/static/picture/pin.png"></image>
          <text class="action-text">评论</text>
        </view>
        <view class="action-item">
          <image class="action-icon" src="/static/picture/zan.png"></image>
          <text class="action-text">赞</text>
        </view>
        <view class="action-item">
          <image class="action-icon" src="/static/picture/eye.png"></image>
          <text class="action-text">插眼</text>
        </view>
      </view>
    </view>
    <view class="message-list">
      <MessageItem
          v-for="(msg, index) in messageList"
          :key="index"
          :avatar="msg.avatar"
          :username="msg.username"
          :lastMessage="msg.lastMessage"
          :unreadCount="msg.unreadCount"
          :userId="msg.userId"
          @close-socket="closeSocket"
      />
    </view>
  </view>
  <FloatingBall />
  <AiChat />
  <custom-tabbar />

</template>

<script setup>
import MessageItem from '@/components/message-list/message-list.vue';
import {onMounted,ref,onUnmounted} from "vue";
import {onShow, onHide } from '@dcloudio/uni-app';
import CustomTabbar from "@/components/custom-tab-bar/my-custom-tab-bar.vue";
import {getMessageList, connectMessageListWebSocket, connectChatWebSocket} from '@/apis/chatAPI'
const messageList = ref([]);
let socketTask = null; // 使用SocketTask替代直接连接

const fetchMessages = () => {
  const userInfo = uni.getStorageSync('userInfo');
  getMessageList(userInfo.userId)
      .then(res => {
        if (res.statusCode === 200) {
          messageList.value = res.data;
          console.log('加载消息成功', res.data);
        } else {
          uni.showToast({ title: res.data.message || '加载消息失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.log('加载消息失败', err);
      });
};

// 初始化WebSocket连接
const initWebSocket = () => {
  const userInfo = uni.getStorageSync('userInfo');
  if (!userInfo || !userInfo.userId) return;

  // 关闭现有连接
  closeSocket();

  // 建立新的WebSocket连接
  // const socketUrl = `ws://localhost:8085/ws/notifications/${userInfo.userId}`;

  // 使用SocketTask API建立连接
  // socketTask = uni.connectSocket({
  //   url: socketUrl,
  //   complete: () => {} // 防止iOS上的"未完成的操作"错误
  // });
  socketTask = connectMessageListWebSocket(userInfo.userId);


  // 监听WebSocket打开
  socketTask.onOpen(() => {
    console.log('通知WebSocket连接成功');
  });

  // 监听WebSocket消息
  socketTask.onMessage((res) => {
    try {
      const notification = JSON.parse(res.data);
      if (notification.type === 'NEW_MESSAGE') {
        handleNewMessageNotification(notification);
      }
    } catch (e) {
      console.error('解析通知失败', e);
    }
  });

  // 监听错误
  socketTask.onError((err) => {
    console.error('通知WebSocket错误', err);
    // 尝试重新连接
    setTimeout(initWebSocket, 3000);
  });
};

// 关闭WebSocket连接
const closeSocket = () => {
  if (socketTask) {
    socketTask.close({
      success: () => console.log('通知WebSocket已关闭'),
      fail: (err) => console.error('关闭WebSocket失败', err)
    });
    socketTask = null;
  }
  console.log('已关闭通知WebSocket');
};

// 处理新消息通知
const handleNewMessageNotification = (notification) => {
  const senderId = notification.senderId;
  const newContent = notification.content;
  const newUnreadCount = notification.unreadCount;

  // 查找对应对话的索引
  const index = messageList.value.findIndex(item => item.userId === senderId);

  if (index !== -1) {
    // 更新现有对话
    const updatedList = [...messageList.value];
    updatedList[index] = {
      ...updatedList[index],
      lastMessage: newContent,
      unreadCount: newUnreadCount
    };

    // 将该对话移到列表顶部
    const updatedItem = updatedList.splice(index, 1)[0];
    updatedList.unshift(updatedItem);

    messageList.value = updatedList;
  } else {
    // 新对话 - 重新加载整个列表
    fetchMessages();
  }
};

onShow(() => {
  fetchMessages();
  initWebSocket();
});

onHide(() => {
  closeSocket();
});

onUnmounted(() => {
  closeSocket();
});
</script>

<style scoped>
.message-page {
  padding: 10px;
}
.message-header {


}
.notification-prompt {
  font-size: 14px;
  height: 40px;
  width: 90%;
  border-radius: 15px;
  /* 设置边框渐变颜色 */
  border: 2px solid;
  color: #333;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  /* 水平居中关键样式 */
  margin-left: auto;
  margin-right: auto;
  padding-left: 20px;
  padding-right: 10px;
}
.manage-button {
  font-size: 14px;
  color: #2C405A;
  background-color: #99FFCC;
  margin-right: 10px;
  width: 80px;
  height: 30px;
}
.message-action {

  display: flex;
  justify-content: space-around;
}
.action-item {
  padding-top: 10px;
  width: 70px;
  height: 70px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.action-icon {
  width: 30px;
  height: 30px;
}
.action-text {
  font-size: 14px;
  margin-top: 5px;
}
.message-list {
  width: 100%;
  height: auto;
  margin-top: 0px;
  overflow-y: auto;
}
</style>
